package com.youlu.campus.service.platform.impl;

import com.alibaba.fastjson.JSON;
import com.youlu.campus.entity.PlatformUserComplaint;
import com.youlu.campus.entity.PlatformUserComplaintConsultRecord;
import com.youlu.campus.entity.VO.req.PlatformUserComplaintReadMsgVO;
import com.youlu.campus.service.platform.PlatformUserComplaintConsultRecordService;
import com.youlu.campus.service.platform.PlatformUserComplaintNotifyService;
import com.youlu.campus.service.platform.PlatformUserComplaintService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class PlatformUserComplaintConsultRecordServiceImpl implements PlatformUserComplaintConsultRecordService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Lazy
    @Autowired
    private PlatformUserComplaintService platformUserComplaintService;
    @Autowired
    private PlatformUserComplaintNotifyService platformUserComplaintNotifyService;

    @Override
    public PlatformUserComplaintConsultRecord create(PlatformUserComplaintConsultRecord record) {
        record.setId(null);
        record.setCreatedTime(new Date());
        record = mongoTemplate.insert(record);
        PlatformUserComplaint platformUserComplaint = platformUserComplaintService.findOne(record.getPlatformUserComplaintId());
        if (Objects.nonNull(platformUserComplaint) && StringUtils.isNotBlank(record.getStatus())) {
            switch (record.getStatus()) {
                case "doing":
                    if (StringUtils.isBlank(platformUserComplaint.getStatus()) || "todo".equals(platformUserComplaint.getStatus())) {
                        PlatformUserComplaint to = new PlatformUserComplaint();
                        to.setId(platformUserComplaint.getId());
                        to.setStatus("doing");
                        if ("visitor".equals(record.getCreateType())) {
                            to.setPlatformHasMsg(true);
                        } else {
                            to.setVisitorHasMsg(Boolean.TRUE);
                        }
                        platformUserComplaintService.update(to);
                    }
                    break;
                case "done":
                    PlatformUserComplaint to = new PlatformUserComplaint();
                    to.setId(platformUserComplaint.getId());
                    to.setStatus("done");
                    if ("visitor".equals(record.getCreateType())) {
                        to.setPlatformHasMsg(true);
                    } else {
                        to.setVisitorHasMsg(Boolean.TRUE);
                    }
                    platformUserComplaintService.update(to);
                    break;
                default:
                    break;
            }
        }
        if ("system".equals(record.getCreateType()) && Boolean.TRUE.equals(record.getSendSms())) {
            platformUserComplaintNotifyService.sendSms(platformUserComplaint);
        }
        return record;
    }

    @Override
    public List<PlatformUserComplaintConsultRecord> findByPlatformUserComplaintId(String platformUserComplaintId) {
        Query query = new Query();
        Sort sort = Sort.by(Sort.Direction.DESC, "createdTime");
        query.with(sort);
        query.addCriteria(Criteria.where("platformUserComplaintId").is(platformUserComplaintId));
        List<PlatformUserComplaintConsultRecord> records = mongoTemplate.find(query, PlatformUserComplaintConsultRecord.class);
        return records;
    }

    @Override
    public HashMap<String, Object> getUnReadMsgCount(String pucId, String createType) {
        Query query = new Query();
        query.addCriteria(Criteria.where("platformUserComplaintId").is(pucId).and("createType").is(createType).and("readedStatus").ne(Boolean.TRUE));
        Long count = mongoTemplate.count(query, PlatformUserComplaintConsultRecord.class);
        HashMap<String, Object> res = new HashMap<>();
        if (Objects.isNull(count) || count.compareTo(0L) != 1) {
            res.put("hasMsg", Boolean.FALSE);
            res.put("count", 0L);
        } else {
            res.put("hasMsg", Boolean.TRUE);
            res.put("count", count);
        }
        return res;
    }

    @Override
    public boolean readMsg(PlatformUserComplaintReadMsgVO req) {
        log.info(":>>> 开始读消息msgIds:{}", JSON.toJSON(req));
        if (Objects.isNull(req.getMsgIds()) || CollectionUtils.isEmpty(req.getMsgIds())) {
            return false;
        }

        Query query = new Query();
        query.addCriteria(Criteria.where("id").in(req.getMsgIds()).and("createType").is(req.getCreateType()));
        Update update = new Update();
        update.set("readedStatus", Boolean.TRUE);
        update.set("readMsgTime", req.getDate());
        update.set("updateTime", req.getDate());
        Query query1 = new Query();
        query1.addCriteria(Criteria.where("id").is(req.getPlatformUserComplaintId()).and("visitorHasMsg").ne(Boolean.FALSE));
        Update update1 = new Update();
        update1.set("visitorHasMsg", Boolean.FALSE);
        update1.set("updatedTime", new Date());
        mongoTemplate.updateFirst(query1, update1, PlatformUserComplaint.class);
        return mongoTemplate.updateMulti(query, update, PlatformUserComplaintConsultRecord.class).getModifiedCount() > 0 ? true : false;
    }

    @Override
    public void updateReadMsgStatus(Date date, String createType) {
        Query query = new Query();
        query.addCriteria(Criteria.where("status").ne("done"));
        List<PlatformUserComplaint> pucs = mongoTemplate.find(query, PlatformUserComplaint.class);
        if (CollectionUtils.isEmpty(pucs)) {
            log.warn(":>>> 不存在待处理、处理中的用户投诉！不处理");
            return;
        }
        log.info(":>>> 需要扫描的平台用户投诉数量:{}", pucs.size());
        for (PlatformUserComplaint puc : pucs) {
            Query query1 = new Query();
            query1.addCriteria(Criteria.where("platformUserComplaintId").is(puc.getId()).and("createType").is("visitor")
                    .and("readedStatus").ne(Boolean.TRUE));
            boolean exist = mongoTemplate.exists(query1, PlatformUserComplaintConsultRecord.class);
            if (!exist) {
                log.info(":>>> 平台用户投诉,不存在访客未读消息:{}", puc.getId());
                Query query2 = new Query();
                query2.addCriteria(Criteria.where("id").is(puc.getId()).and("visitorHasMsg").ne(Boolean.FALSE));
                Update update = new Update();
                update.set("visitorHasMsg", Boolean.FALSE);
                update.set("updatedTime", date);
                mongoTemplate.updateFirst(query2, update, PlatformUserComplaint.class);
                continue;
            }
            log.info(":>>> 平台用户投诉,存在访客未读消息,需要更新后台状态:{}", puc.getId());
            Query query2 = new Query();
            query2.addCriteria(Criteria.where("id").is(puc.getId()).and("visitorHasMsg").ne(Boolean.TRUE));
            Update update = new Update();
            update.set("visitorHasMsg", Boolean.TRUE);
            update.set("updatedTime", date);
            mongoTemplate.updateFirst(query2, update, PlatformUserComplaint.class);

        }


    }
}
